﻿using System;
using System.Web.Script.Serialization;
using System.Web.UI;

namespace Otgruzka.Controls.jQuery
{
    public class JQueryControlsBase : System.Web.UI.UserControl
    {
        private ScriptManager _currentScriptManager;
        protected ScriptManager CurrentScriptManager
        {
            get
            {
                if (_currentScriptManager == null)
                {
                    _currentScriptManager = ScriptManager.GetCurrent(Page);
                }
                return _currentScriptManager;
            }
        }

        protected void RegisterScriptReference(string path)
        {
            if (CurrentScriptManager != null)
            {
                CurrentScriptManager.Scripts.Add(new ScriptReference(path));
            }
        }

        protected void RegisterPlugin(string containerClientId, string pluginName, object clientSettings)
        {
            ScriptManager.RegisterStartupScript(
                this.Page,
                this.GetType(),
                "InitializeJS" + Guid.NewGuid().ToString(),
                "jQuery( function() { jQuery('#" + containerClientId + "')." + pluginName + "(" + new JavaScriptSerializer().Serialize(clientSettings) + ").Initialize(); });",
                true
                );
        }

        protected override void OnInit(EventArgs e)
        {
            //Регистрируем скрипты, необходимые для работы контролов
            //RegisterScriptReference("~/JScripts/jquery-1.6.4.min.js");
            RegisterScriptReference("~/Scripts/jquery/js/jquery-ui-1.8.16.custom.min.js");
            RegisterScriptReference("~/Scripts/jquery/js/jquery.ui.datepicker-ru.js");
            RegisterScriptReference("~/Scripts/jquery/js/jquery.tools.min.js");
            RegisterScriptReference("~/Scripts/JQueryControls.js");
            RegisterScriptReference("~/Scripts/TypeUtilities.js");
        }
    }
}